mod core;

use crate::core::*;

use anyhow::Context;

use std::fs;

#[inline]
fn get_config() -> anyhow::Result<GenConfig> {
    let path = "./config/base.json";
    let content = fs::read_to_string(path)?;
    let config = serde_json::from_str(&content)?;
    Ok(config)
}

fn main() -> anyhow::Result<()> {
    let config = get_config().context("Fail to get config !")?;

    // println!("{:?}", config);

    let mut generator = MapGen::new(config).context("Fail to initialize the generator !")?;

    println!(
        "Running with the seed : {} ......",
        generator.config.random_seed.unwrap()
    );

    generator
        .gen_water()
        .unwrap_or_else(|err| println!("{} while generating water", err));

    generator
        .gen_height()
        .unwrap_or_else(|err| println!("{} while generating the high ground ", err));

    generator.gen_ramp()?;

    #[cfg(debug_assertions)]
    {
        for element in generator.base.iter() {
            for element in element.iter() {
                assert!(element.captured != Captured::PlayerSpawn);
            }
        }
    }

    match generator.set_player() {
        Ok(_) => {}
        Err(err) => {
            return Err(err.into());
        }
    }

    generator.base_parse();

    let save_dir = r#"C:\Develop\Projects\ra3_cs_script\hello_world"#;

    generator.save_parse(save_dir).with_context(|| {
        format!(
            "Fail to save the data files at the directory : {} !",
            save_dir
        )
    })?;

    generator.display_base();

    Ok(())
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn gen_config() {
        let config: GenConfig = Default::default();
        let content = serde_json::to_string(&config).unwrap();
        fs::write("./config/base.json", &content).unwrap();
    }
    use image::{Rgb, RgbImage};
    #[test]
    fn image_test() -> anyhow::Result<()> {
        let (width, height) = (1000, 1000);
        let mut image_buf = RgbImage::new(width, height);
        for i in 0..width {
            for j in 0..height {
                image_buf.put_pixel(i, j, Rgb([0, 0, 0]));
            }
        }
        for i in 100..200 {
            for j in 200..500 {
                image_buf.put_pixel(i, j, Rgb([100, 100, 100]));
            }
        }
        image_buf.save("./out/image.png")?;

        Ok(())
    }
}
